package com.zby.controller.article;

import com.google.common.util.concurrent.RateLimiter;
import com.zby.common.exception.BlogException;
import com.zby.common.utils.ResultUtil;
import com.zby.model.pojo.CustomUserDetails;
import com.zby.service.LikeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Min;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/likes")
@Tag(name = "文章点赞管理")
public class ArticleLikesController {
    @Resource
    @Qualifier("likeRateLimiter")
    // 注入限流器
    private RateLimiter likeRateLimiter;
    @Resource
    private LikeService likeService;

    /**
     * 点赞和取消功能
     */
    @PostMapping("/toggle")
    @Operation(summary = "文章点赞")
    public ResultUtil<Integer> toggleLike(@RequestParam Long articleId,@RequestParam Integer id ) {
        if (articleId == null || articleId <= 0) {
            throw new BlogException(4000, "文章ID必须大于0");
        }
        // 判断用户是否登录
//        if (userDetails == null) {
//            throw new BlogException(4100, "请先登录");
//        }
        // 限流控制 (每秒最多5次操作)
        if (!likeRateLimiter.tryAcquire()) {
            throw new BlogException(429, "操作过于频繁，请稍后再试");
        }
        Integer result = likeService.toggleLike(articleId, id);

        return ResultUtil.success(result);
    }
}
